/**
  * @description: 订单列表
  * @author: yingying.fan
  * @date: 2019/2/25 11:18
  */
import React, { Component } from 'react'
import { StyleSheet, SafeAreaView, DeviceEventEmitter } from 'react-native'
import { px2dp, LogUtils } from 'rn-xiaobu-utils'
import { getOrderListByFilter } from '../api/OrderApi'
import OrderItem from '../components/orderlist/OrderItem'
import PullList from '../widgets/PullList'
import { deleteOrderAction, changeOrderList } from '../actions/OrderAction'

import { connect } from 'react-redux'
import SegmentedTab from '../widgets/SegmentedTab'
import { appThemeColor } from '../configs/appconfig'
import { OrderOptionEvent, OrderOptionTypes } from '../utils/OrderOptionUtils'
import NavigationService from '../../src/utils/NavigationService'

class OrderListPage extends Component {
  static navigationOptions = {
    headerTitle: '订单列表'
  }

  constructor (props) {
    super(props)

    this.orderTabType = 0
    this.state = {
      index: 0,
      dataList: []
    }
  }

  componentWillMount () {
    this.routeName = this.props.navigation.state.routeName
    LogUtils.log('routeName:' + this.routeName)
    switch (this.routeName) {
      case 'AllOrder':
        this.orderTabType = 0
        break
      case 'PayOrder':
        this.orderTabType = -1
        break
      case 'DeliverOrder':
        this.orderTabType = 1
        break
      case 'ReceiveOrder':
        this.orderTabType = 2
        break
      case 'CommentOrder':
        this.orderTabType = 3
        break
      default:
        break
    }

  }

  componentDidMount (): void {
    this.orderListener = DeviceEventEmitter.addListener(
      OrderOptionEvent,
      eventInfo => {
        LogUtils.log('接收事件:orderOption', eventInfo)
        let type = eventInfo.type
        let orderIndx = eventInfo.info.INDEX
        switch (type) {
          case OrderOptionTypes.DELETE:
            this.props.dispatch(deleteOrderAction(orderIndx))
            break
          case OrderOptionTypes.CLOSE:
            if (this.orderTabType !== 0) {
              this.props.dispatch(deleteOrderAction(orderIndx))
            } else {
              // TODO: 刷新该笔订单数据
            }
            break
        }
      })
  }

  componentWillUnmount (): void {
    if (this.orderListener) {
      this.orderListener.remove()
    }
  }

  _changeOrderTab = index => {
    LogUtils.log('index:' + index)
    this.setState({ index: index })
    switch (index) {
      case 0:
        this.orderTabType = 0
        break
      case 1:
        this.orderTabType = -1
        break
      case 2:
        this.orderTabType = 1
        break
      case 3:
        this.orderTabType = 2
        break
      case 4:
        this.orderTabType = 3
        break
      default:
        break
    }

    this.refs.pullList._onHeaderRefresh()
  }

  _getList = (pageIndex, pageSize) => {
    return getOrderListByFilter(this.orderTabType, pageIndex, pageSize)
      .then(body => {
        let list = body.LIST
        if (pageIndex !== 1) {
          list = this.props.dataList.concat(list)
          // list = this.state.dataList.concat(list)
        } else {
          try {
            this.refs.pullList._scrollToTop()
          } catch (e) {
            LogUtils.error('_scrollToTop', e)
          }
        }
        // this.setState({
        //   dataList: list
        // })
        this.props.dispatch(changeOrderList(list))
        return { length: list.length, count: body.COUNT }
      })
  }

  _parseItem = ({ item, index }) => {
    return (
      <OrderItem
        orderIndex={index}
        orderInfo={item}
        onPress={() => this._goToOrderDetail(item.ORDER_ID)}
      />
    )
  }

  _goToOrderDetail = (orderId) => {
    LogUtils.log('跳转到订单详情' + orderId)
    NavigationService.push('OrderDetail',
      { orderId: orderId })
  }

  render () {
    return (
      <SafeAreaView style={styles.container}>
        <SegmentedTab
          titles={['全部', '待支付', '待发货', '待收货', '待评价']}
          index={this.state.index}
          select={this._changeOrderTab}
          titleStyle={styles.tabTitleStyle}
          titleSelectedStyle={styles.tabTitleSelectedStyle}
          lineSelectedStyle={styles.tabLineSelected}/>
        <PullList
          ref="pullList"
          // data={this.state.dataList}
          data={this.props.dataList}
          renderItem={this._parseItem}
          getDataList={this._getList}
          extraData={this.props}
        >
        </PullList>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#f2f5f6'
  },
  wrapper: {
    width: px2dp(690),
    height: px2dp(100),
    backgroundColor: '#aff'
  },
  tabTitleStyle: {
    color: '#333',
    fontSize: px2dp(28)
  },
  tabTitleSelectedStyle: {
    color: appThemeColor
  },
  tabLineSelected: {
    position: 'absolute',
    bottom: 0,
    width: '50%',
    height: px2dp(6),
    backgroundColor: appThemeColor
  }
})

// 将页面与store内的state、action关联在一起，实现视图部分与逻辑处理部分的关联
export default connect(
  (state) => ({
    dataList: state.order2Reducer.dataList
    // orderId: state.order2Reducer.orderId
  }),
  (dispatch) => ({
    dispatch: dispatch
    // deleteOrderAction: (item, index) => dispatch(deleteOrderAction(item, index)),
    // changeOrderList: (list) => dispatch(changeOrderList(list))
  })
)(OrderListPage)

// export default OrderListPage
